// packageA/pages/cleanWorkAdd/cleanWorkAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //当前用户
    user: null,
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{
			//预计完成时间（一天后）
			planCompletionTime: util.timeFormatDay(util.countNextDay(new Date(),1)) + ' 23:59:59'
		},
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,
    //工作区域选择框
    showWorkAreaSelect:false,
    //选择框
    showSelect:false,
    //选择工作区域数据
    selectWorkList:[],
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
		showSelectSearch:false,
		//时间选择框
    showTime:false,
    //当前时间
		currentTime: new Date().getTime(),
		//最小时间
    minDate: new Date().getTime(),
    //区域全选/反选
    checkedAllArea: false,
    //区域选项
    checkDetailArea: [],
    //保洁人员
    clearer:[],
    //保洁人员选择框
    showClearer:false,
    //保洁工单接收人id
    cleanOrderMessageReceive:[],
    //接单内容
    receiveOrderObj:{},
    listCleanOrderMap: {},
    //随机数位数
    randomDigits:3,
    propertyAbbr:'WO',
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    console.log(options);

    this.setData({
      code: Base64.encode(new Date() + app.globalData.userInfo.userName),
      user: app.globalData.userInfo,
      listCleanOrderMap: new Map()
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('保洁工单传参');
      console.log(paramObj);
      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit:true
        })
        //获取修改数据
        this.getInfo();

        if(paramObj.isReceive){
          //查询项目设置里，保洁工单接收人
          this.findClearOrderMessageReceive(paramObj.projectId)
          this.setData({
            receiveOrderObj:{
              place:paramObj.place,
              problem:paramObj.problem,
              projectName:paramObj.projectName
            }
          })
        }
			}
    }
  },
  

  findClearOrderMessageReceive(projectId){
		let dataObj={
			selectFields: ['id','name','cleanLeader','cleanOrderUsers'],
      id:projectId
		}
		let param = {
      className: 'depart',
      data: dataObj
		}

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        console.log('保洁工单接收人');
        console.log(result); 
        if (result!=null && result.length>0){
          if (result[0].cleanLeader != null){
            this.setData({
              cleanOrderMessageReceive:result[0].cleanOrderUsers
            })
          }
        }
      }
    }).catch((error) => {
     
    })
  },


	//提交表单
  confirmForm(e){
		let obj=e.detail.value;

		if(this.data.paramObj && this.data.paramObj.isReceive){
			//接单
			this.receiveForm(obj);
		}else{
			this.saveForm(obj);
		}
	},

  //添加/修改表单
  saveForm(obj){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
		})
		
    let td=this.data;
    let editInfo=td.editInfo;
    let user=td.user;

    console.log(editInfo);
  

    //非空验证
    if(!editInfo.project){
      Toast.fail('请选择项目');
      return;
    }

    if(!editInfo.clearer && JSON.stringify(editInfo.clearer) !== '{}'){
      Toast.fail('请选择保洁员');
      return;
    }



    let place=obj.place.trim();
    if(!this.formNotEmpty(place,'placeMessage','请输入地点')){
      return;
    }

    let problem=obj.problem.trim();
    if(!this.formNotEmpty(problem,'problemMessage','请输入问题描述')){
      return;
    }

    let param={
      className:'cleanKeepingOrder',
      data:{
        requestToken: td.code,
        id: td.id,
        //地点
        place: place,
        //问题
        problem: problem,
        //图
        pic: editInfo.pic,
        //备注
				remark: obj.remark.trim(),
				//预计完成时间
        planCompletionTime: editInfo.planCompletionTime,
        //工作区域
        workArea:editInfo.workArea,
        //保洁员：
        handler:editInfo.clearer,
        //工作区域id
        workAreaIdArr:editInfo.workAreaIdArr,
        //工单编号
        orderNo:this.generateId()
      }
		}
					//项目
          param.data.project={
            id: editInfo.project.id,
            name: editInfo.project.name,
            address: editInfo.project.address,
            area: editInfo.project.area
          }
		//添加时		
		if(!td.isEdit){


			//数据权限
			let authArr=[user.depart, user.departObj[0].companyId, user.departObj[0].fid, editInfo.project.id].concat(user.departObj[0].cleaningSupplier);
			authArr=util.arrayRepeatEmpty(authArr); 

			param.data.dataAuthority={
				depart: authArr
			}

			//提交人（创建人）
			param.data.submitter = {
				id: user.id,
				name: user.userName,
				phone: user.personalPhone
			}

			//提交时间
			param.data.submissionTime = util.timeFormat(new Date());
			
			//状态（1已完成,2待接单,3处理中）
			param.data.state = 2;
		}

   
      console.log(param);
     // this.pushMessage(param.data)
    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');  
        this.sendMessageTTS(param.data);
        this.pushMessage(param.data)
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        console.log(res);
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      console.log(error)
      Toast.fail('操作失败');
    })
	},
  generateRandomNumber(digits) {
    const min = Math.pow(10, digits - 1);
    const max = Math.pow(10, digits) - 1;
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },
  generateId(){
    const timestamp = new Date().getTime().toString();
    const timestampSuffix = timestamp; // 取时间戳后8位
    const randomNum = this.generateRandomNumber(this.data.randomDigits);
    return this.data.propertyAbbr+`-${timestampSuffix}${randomNum}`;
  },

	//接单
	receiveForm(obj){
    console.log(obj);
    console.log(this.data)
		//避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
		})
		
		let user = this.data.user;

    console.log(user);
    
		//手机号
		let phone=obj.phone.trim();

    if(!this.formNotEmpty(phone,'phoneMessage','请输入手机号')){
      return;
		}
    
    if(!util.checkPhoneFormat(phone)){
      this.setData({
        phoneMessage: '手机号格式错误',
        disabled: true
      })
      return;
    }

		let param={
			className:"cleanKeepingOrder",
			data:{
				id: this.data.paramObj.id,
				//状态 1已完成,2待接单,3受理中
				state: 3,
				//预计完成时间
			//	planCompletionTime: this.data.editInfo.planCompletionTime,
				//接单时间
				handlingTime: util.timeFormat(new Date()),
				//接单人
				handler: {
					id: user.id,
          name: user.nickName,
          imei: user.imei,
					phone: phone
				}
			}
    }			
    console.log(this.data.receiveOrderObj)
    console.log("param");
    console.log(param);


		CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');  
        //公众号发送消息
        if (this.data.cleanOrderMessageReceive!=null && this.data.cleanOrderMessageReceive.length>0){
          // 使用 map 方法提取 id 并生成新数组
          const idArray = this.data.cleanOrderMessageReceive.map(item => item.id);
          let sendParam={
            //接收人user表id（工单创建人）
            userId: idArray,
            file: 'cleaningWorkOrderState',
            //跳转
            jump: true,
            data:{
              //项目名
              thing31: this.data.receiveOrderObj.projectName,
              //接单人
              phrase14: param.data.handler.name.split("-")[0],
              //工单标题（投诉问题）
              //thing33: this.data.receiveOrderObj.problem+"(处理人:"+param.data.handler.name+")",
              thing33: this.data.receiveOrderObj.problem,
              //工单状态（投诉地点）
              phrase15: '已接单',
              //通知时间
              time10: util.timeFormat(new Date())
            }
          } 
          CommonService.sendMessage(sendParam).then(res=>{
          }).catch((error) => {
          })
        }
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
	},


  	//推送消息
	pushMessage(row){

		let param={
			//接收人user表id（处理人）
			userId: [row.handler.id],
			file: 'cleaningWorkOrder',
			//跳转
			jump: true,
			data:{
				//项目名
				thing31: row.project.name,
				//创建时间
				time51: util.timeFormat(new Date()),
				//工单标题（投诉问题）
				thing33: row.problem,
				//发生地址（投诉地点）
				thing53: row.place,
				//工单状态
				phrase15: '待接单'
			}
    } 
    
    console.log(param);

		CommonService.sendMessage(param).then(res=>{
    }).catch((error) => {
    })
	},

  //发送语音
  sendMessageTTS(row){
    let ttsContent = "地点"+row.place+","+row.problem;
    console.log(ttsContent);
    if (row.handler && row.handler.imei != null && row.handler.imei != ""){
      let data = {
            "url":"/sendMessageToDevice",
            "body":{
                "imei":row.handler.imei,
                "content": ttsContent,
                "type": 0,
                "voice" : "ruoxi"
            }
        }
        CommonService.sendMessageTTS(data).then(res=>{
          console.log("TTS语音");
          console.log(res);
        }).catch((error) => {
        })
    }

  },

  //获取修改数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'cleanKeepingOrder',
      data: {
        id:this.data.id,
				selectFields: ['id','project','place','problem','remark','pic','planCompletionTime','handler','workAreaIdArr','workArea'],
				nbl: Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('保洁工单信息回显');
				console.log(result);
				
				//预计完成时间
				if(result.planCompletionTime){
					result.planCompletionTime = util.timeFormat(result.planCompletionTime);
				}else{
					result.planCompletionTime = util.timeFormatDay(util.countNextDay(new Date(),1)) + ' 23:59:59'
        }

        result.clearer= result.handler
        let names=[];
        if(result.workArea){
           result.workArea.forEach(item=>{
            names.push(item.name);
           })
           result.self_workArea = names
        }
        this.setData({
          editInfo: result
        })

      }
    }).catch((error) => {
    })
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;
    let pic='editInfo.pic';

    if(imgUrls.length){
      this.setData({
        [pic]: imgUrls
      })
    }else{
      this.setData({
        [pic]: null
      })
    }
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //显示工作区域选择框
  onShowWorkAreaPersonnel(e){
      this.setData({
        selectWorkList:[],
      })
      let dataset=e.currentTarget.dataset;
      let field=dataset.field;
      console.log(field);

      this.setData({
        selectTitle:"工作区域",
        showWorkAreaSelect: true,
        selectField: field
      })

      this.getWorkAreaList();
  },


  //显示保洁人员
  onShowCleaner(e){
    this.setData({
      selectWorkList:[],
    })
    let dataset=e.currentTarget.dataset;
    let field=dataset.field;
    console.log(field);

    this.setData({
      selectTitle:"工作区域",
      showWorkAreaSelect: true,
      selectField: field
    })

    this.getWorkAreaList();
},


  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //项目
    if(field=='project'){
      this.setData({
        selectTitle: '项目',
        showSelectSearch: true
      })
      this.getProjectList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  onCancelClearerSelect(){
    this.setData({
      showClearer: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //项目
    if(selectField=='project'){
      obj='editInfo.project';      
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  
onConfirmClearerSelect(e){
  console.log(e);
  this.setData({
    disabled:true
  })
  let obj = 'editInfo.clearer'
  this.setData({
    [obj]:{
      id:e.detail.value.id,
      name:e.detail.value.text,
      imei:e.detail.value.imei
    },
    disabled:false,
    showClearer:false
  })
  
},

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //项目
    if(selectField=='project'){
      obj='editInfo.project';     
    }

    if(id && name){
      this.setData({
        [id]:null,
        [name]:''
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //项目
    if(selectField=='project'){
      this.getProjectList();
    }
  },

  //查询工作区域
  getWorkAreaList(){
    console.log("this.data");
    console.log(this.data.editInfo.project.id);
    let param = {
      isAuth: true,
      className: 'workAreaP',
      data: {
        projectId:this.data.editInfo.project.id,
				searchAll: true,
        selectFields: ['id','name','workAreaTypeName','attribute'],
        sort:{workAreaTypeId:1,attribute:1,name:1}
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }
    console.log(param);
    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        console.log("result");
        console.log(result);
        let arr=[];
        result.forEach(item => {
          arr.push({
            name:item.attribute+"-"+item.name,
            id:item.id,
          });
        });
        if(this.data.editInfo&&this.data.editInfo.workArea){
          console.log(this.data.editInfo)
          console.log("编辑")
          console.log("进来了");
          console.log(this.data.editInfo);
          let map=new Map();
          this.data.editInfo.workArea.forEach(item => {
            map.set(item.id,item);
          });
          //复选框选中状态
          let userList=arr;
          userList.forEach(item => {
            if(map.get(item.id)){
              console.log(item);
              item.checked=true;
            }
          });
          console.log("userList");
          console.log(userList);

          this.setData({
            listCleanOrderMap:map,
            selectWorkList: userList
          })
        }else{
          this.setData({
            selectWorkList: arr
          })
        }

      
      }
    }).catch((error) => {
    })
  },
 //点击区域明细选项
 onChangeDetailArea(event) {
  console.log("event");
   console.log(event);
  this.setData({
    checkDetailArea: event.detail
  })

  if(event.detail.length==this.data.checkLenArea){
    this.setData({
      checkedAllArea: true
    })
  }else{
    this.setData({
      checkedAllArea: false
    })
  }

},


onChangeCleanOrderCheck({currentTarget}) {
  let detail=currentTarget.dataset.detail;
  let list=this.data.selectWorkList;
  let listMap=this.data.listCleanOrderMap;
  console.log(detail);
  console.log(list);
  console.log(listMap);
  list.forEach(item => {
    if(item.id==detail.id){
      //点击复选框时切换选中
      item.checked=!item.checked;
      if(item.checked){
        //选中的放入已选列表，利用map避免重复
        listMap.set(item.id,item);
      }else{
        //未选中的从map中删除
        listMap.delete(item.id);
      }
    }
  });

  //列表是否全被选中了
  let flag=list.every(item=>{
    return item.checked;
  });

  //是否选中全选
  if(flag){
    this.setData({
      checkedAll: true
    })
  }else{
    this.setData({
      checkedAll: false
    })
  }

  this.setData({
    selectWorkList: list,
    listCleanOrderMap: listMap
  })
},


//确定清洁区域按钮
onConfirmArea(){
  let listMap=this.data.listCleanOrderMap;
  //map转成数组
  let arr=[...listMap.values()];
  if (arr.length){
      //名字
      let arr1=[];
      let names=[];
      let idarr=[];
      arr.forEach(item => {
        names.push(item.name);
        idarr.push(item.id);
        arr1.push(item)
      });
       //显示名称
       let self_name='editInfo.self_workArea';
       //接口保存数据
       let items='editInfo.workArea';
       let workAreaIdArr = 'editInfo.workAreaIdArr'
       let clearer = "editInfo.clearer"
       this.setData({
        [self_name]: names,
        [items]: arr,
        [workAreaIdArr]:idarr,
        [clearer]:null,
        showWorkAreaSelect: false,
        disabled: false
      })
      //根据选中的工作区域筛选出保洁人员
      this.findPersonnelByWorkArea(idarr);
  }else{
    Toast.fail('请选择清洁区域');
  }

  



    // console.log(this.data);
    // let checkDetail=arr;
    // //所有工作区域
    // if(checkDetail.length){
    //   let list=this.data.selectWorkList;
    //   let arr=[];
    //   let names=[];
    //   let idarr=[];
    //   list.forEach(item => {
    //     for(let i=0;i<checkDetail.length;i++){
    //       if(checkDetail[i]==item.id){
    //         console.log("相等");
  
    //       }
    //     }
    //   });
    //    //显示名称
    //    let self_name='editInfo.self_workArea';
    //    //接口保存数据
    //    let items='editInfo.workArea';
    //    let workAreaIdArr = 'editInfo.workAreaIdArr'
    //    this.setData({
    //     [self_name]: names,
    //     [items]: arr,
    //     [workAreaIdArr]:idarr,
    //     showWorkAreaSelect: false,
    //     disabled: false
    //   })

    // }else{
    //   Toast.fail('请选择清洁区域');
    // }
},

  //点击全选区域
  onChangeAllArea(event) {
    this.setData({
      checkedAllArea: event.detail,
    })

    if(event.detail){
      let list=this.data.selectWorkList;
      let arr=[];
      list.forEach(item => {
        arr.push(item.id+'');
      })
      this.setData({
        checkDetailArea: arr,
      })
    }else{
      this.setData({
        checkDetailArea: [],
      })
    }
  },

//根据选中的工作区域筛选出保洁人员
findPersonnelByWorkArea(idarr){
  let data = {
    workArea:idarr
  }
  console.log(data);
  CommonService.findClearPersonnelByWorkArea(data).then(res=>{
    if(res.data.data && res.data.data.result && res.data.data.result.length){
      let result=res.data.data.result;
      console.log("result");
      console.log(result);
      let clearer = [];
      if (result!=null && result.length>0){
        result.forEach(item=>{
          clearer.push({
            id:item.id,
            text:item.nickName,
            imei:item.imei
          })
        });
        this.setData({
          clearer:clearer
        })
      }
    }
  }).catch((error) => {
  })
},


  //隐藏区域
  onCloseArea(){
    this.setData({
      showWorkAreaSelect: false
    })
  },


  //查询项目
  getProjectList(){
    let param = {
      isAuth: true,
      className: 'depart',
      data: {
				searchAll: true,
				isProject: true,
        selectFields: ['id','name','address','area','cleanLeader']
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id: item.id,
              name: item.name,
              address: item.address,
              area: item.area,
              cleanLeader: item.cleanLeader
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },
	
	//显示时间
  onShowTime(){
    this.setData({
			showTime: true
    })
  },

  //隐藏时间
  onCloseTime(){
    this.setData({
			showTime: false
    })
  },

  //确认时间
  onConfirmTime(e) {
    let planCompletionTime = 'editInfo.planCompletionTime';
    this.setData({
      currentTime: e.detail,
      [planCompletionTime]: util.timeFormat(e.detail),
    })
    this.onCloseTime();
  },

  //选择人员
  onShowClearerSelect(){
    console.log(this.data)
      this.setData({
        showClearer:true,
        selectTitle:"保洁人员",
        clearer:this.data.clearer
      })
      console.log(this.data.clearer);
      //根据选中的工作区域筛选出保洁人员
      this.findPersonnelByWorkArea(this.data.editInfo.workAreaIdArr);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
